﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2010.License;
using ServBus.ListForm2010.Utility;

namespace ServBus.ListForm2010.TimerJob
{
    public class ClearAttDoclib : SPJobDefinition
    {
        internal static readonly string JOB_NAME = "InfoBus ListForm Clear Attachments Cache";

        public ClearAttDoclib()
        {
        }

        public ClearAttDoclib(SPWebApplication webapp)
            : base(JOB_NAME, webapp, null, SPJobLockType.Job)
        {
            base.Title = JOB_NAME;
        }

        public ClearAttDoclib(string jobName, SPService service, SPServer server, SPJobLockType lockType)
            : base(jobName, service, server, lockType)
        {
            base.Title = JOB_NAME;
        }

        private void ClearSingleWeb(Guid siteId, Guid webId)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (SPSite site = new SPSite(siteId))
                    {
                        using (SPWeb web = site.OpenWeb(webId))
                        {
                            Guid doclibId = new Guid(web.Properties[Constants.ATT_LIB_KEY]);
                            SPList doclib = web.Lists[doclibId];
                            SPQuery query = new SPQuery();
                            query.Query = string.Format("<Where><And><Eq><FieldRef Name='FSObjType' /><Value Type='Text'>1</Value></Eq>" +
                                "<Lt><FieldRef Name='Last_x0020_Modified'/><Value Type='DateTime' IncludeTimeValue='TRUE'>{0}</Value></Lt></And></Where>",
                                Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddMinutes(-30)));

                            SPListItemCollection clearItems = doclib.GetItems(query);
                            for (int i = clearItems.Count - 1; i >= 0; i--)
                            {
                                // Xsn Resource
                                string id = clearItems[i].DisplayName;
                                if (id.StartsWith(Constants.XSN_CACHE_PREFIX))
                                {
                                    id = id.Substring(Constants.XSN_CACHE_PREFIX.Length);
                                    try
                                    {
                                        SPFile xsnFile = web.GetFile(new Guid(id));
                                        if (!xsnFile.Exists)
                                            clearItems[i].Delete();
                                    }
                                    catch
                                    {
                                        clearItems[i].Delete();
                                    }
                                }
                                else
                                {
                                    clearItems[i].Delete();
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorLog.Write(siteId.ToString() + ":" + webId.ToString() + Environment.NewLine +
                    ex.Message + Environment.NewLine + ex.StackTrace,
                     System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webapp = this.Parent as SPWebApplication;
            try
            {
                Activations acts = new Activations(webapp);
                foreach (ActivationInfo actInfo in acts.Infos)
                {
                    ClearSingleWeb(actInfo.SiteId, actInfo.WebId);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.Write(ex.Message + Environment.NewLine + ex.StackTrace,
                     System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public static void InstallToWebapp(SPWebApplication webapp)
        {
            // Remove first
            RemoveFromWebapp(webapp);

            // Then, install
            ClearAttDoclib job = new ClearAttDoclib(webapp);
            //SPDailySchedule schedule = new SPDailySchedule();
            //schedule.BeginHour = 2; schedule.EndHour = 3;
            //schedule.BeginMinute = 0; schedule.EndMinute = 59;
            //schedule.BeginSecond = 0; schedule.EndSecond = 59;
            SPHourlySchedule schedule = new SPHourlySchedule();
            schedule.BeginMinute = 0; schedule.EndMinute = 59;
            job.Schedule = schedule;
            job.Update();
        }

        public static void RemoveFromWebapp(SPWebApplication webapp)
        {
            foreach (SPJobDefinition job in webapp.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                {
                    job.Delete();
                    break;
                }
            }
        }
    }
}
